package com.huiyin.ui.home;

import java.io.File;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.huiyin.R;
import com.huiyin.UIHelper;
import com.huiyin.api.URLs;
import com.huiyin.js.JsInterface;
import com.huiyin.js.JsInterface.BackBtnClickListener;
import com.huiyin.js.JsInterface.WebViewClientClickListener;
import com.huiyin.utils.FileUtils;
import com.huiyin.utils.LogUtil;
/**
 * 投票活动
 * 
 * zhyao
 */
public class VoteActivity extends Activity {

	public static final String TAG = "VoteActivity";
	
	public static final int FILECHOOSER_RESULTCODE = 1;
	/**
	 * 照相
	 */
	private static final int REQ_CAMERA = FILECHOOSER_RESULTCODE+1;
	
	/**
	 * 相册
	 */
	private static final int REQ_CHOOSE = REQ_CAMERA+1;
	/**
	 * 图片回调地址
	 */
	private ValueCallback<Uri> mUploadMessage;
	/**
	 * webview
	 */
	private WebView mWebView;
	/**
	 * Java与JS交互接口
	 */
	private JsInterface jsInterface = new JsInterface();
	/**
	 * 相册图片保存路径
	 */
	private String compressPath = "";
	/**
	 * 拍照图片保存路径
	 */
	private String imagePaths;
	/**
	 * 拍照图片Uri
	 */
	private Uri cameraUri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_try_apply);

		initViews();

		loadWebData();
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void initViews() {
		mWebView = (WebView) findViewById(R.id.webView);
		
		WebSettings webSettings = mWebView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
		webSettings.setAllowFileAccess(true);
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
			webSettings.setAllowFileAccessFromFileURLs(true);
		}
		
		mWebView.addJavascriptInterface(jsInterface, "JSInterface");
		
		mWebView.setWebChromeClient(new MyWebChromeClient());

		mWebView.setWebViewClient(new WebViewClient() {
			
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				LogUtil.d(TAG, "shouldOverrideUrlLoading: " + url);
				if (url != null) {
					if(url.contains("s.share.baidu.com")) {
						Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					    startActivity(i);					
					}
					else {
						view.loadUrl(url);
					}
				}
				return true;
			}
		});
		
		jsInterface.setBackBtnClickListener(new BackBtnClickListener() {
			
			@Override
			public void backEnvent() {
				VoteActivity.this.finish();
			}
		});
		
		jsInterface.setWebViewClientClickListener(new WebViewClientClickListener() {
			
			@Override
			public void wvHasClickEnvent(String action, String args) {
				LogUtil.d(TAG, "wvHasClickEnvent : action = " + action);
				LogUtil.d(TAG, "wvHasClickEnvent : args = " + args);
				JSONArray jsonArray;
				JSONObject jsonObject;
				//复制内容到系统剪切板
				if("clipboar".equals(action)) {
					try {
						jsonArray = new JSONArray(args);
						jsonObject = (JSONObject) jsonArray.get(0);
						String value = jsonObject.getString("value");
						ClipboardManager cmb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
						cmb.setText(value);
						UIHelper.showToast("已复制到系统剪切板");
					} catch (JSONException e1) {
						e1.printStackTrace();
					}
				}
			}
		});
	}

	private void loadWebData() {
//		mWebView.loadUrl("file:///android_asset/upload_image.html");
//		mWebView.loadUrl("http://192.168.200.109:8080/x5/UI2/hello/www/page/vote/view/vote.html");
		mWebView.loadUrl(URLs.vote_activity);
	}

	private class MyWebChromeClient extends WebChromeClient {

		// For Android 3.0+
		public void openFileChooser(ValueCallback<Uri> uploadMsg,
				String acceptType) {
			if (mUploadMessage != null)
				return;
			mUploadMessage = uploadMsg;
			//selectImage();
			//暂时去除拍照,保留相册start
			if (!checkSDcard())
				return;
			chosePic();
			compressPath = Environment
					.getExternalStorageDirectory().getPath()
					+ "/huiyinlehu/temp";
			new File(compressPath).mkdirs();
			compressPath = compressPath + File.separator +  (System.currentTimeMillis() + ".jpg");
			//暂时去除拍照，保留相册end
			// Intent i = new Intent(Intent.ACTION_GET_CONTENT);
			// i.addCategory(Intent.CATEGORY_OPENABLE);
			// i.setType("*/*");
			// startActivityForResult( Intent.createChooser( i, "File Chooser"
			// ), FILECHOOSER_RESULTCODE );
		}

		// For Android < 3.0
		public void openFileChooser(ValueCallback<Uri> uploadMsg) {
			openFileChooser(uploadMsg, "");
		}

		// For Android > 4.1.1
		public void openFileChooser(ValueCallback<Uri> uploadMsg,
				String acceptType, String capture) {
			openFileChooser(uploadMsg, acceptType);
		}

	}

	/**
	 * 检查SD卡是否存在
	 * 
	 * @return
	 */
	public final boolean checkSDcard() {
		boolean flag = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
		if (!flag) {
			UIHelper.showToast("请插入手机存储卡再使用本功能");
		}
		return flag;
	}

	/**
	 * 选择图片方式:拍照和相册
	 */
	protected final void selectImage() {
		if (!checkSDcard())
			return;
		String[] selectPicTypeStr = { "拍照", "相册" };
		new AlertDialog.Builder(this).setItems(selectPicTypeStr,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						// 相机拍摄
						case 0:
							openCarcme();
							break;
						// 手机相册
						case 1:
							chosePic();
							break;
						default:
							break;
						}
						compressPath = Environment
								.getExternalStorageDirectory().getPath()
								+ "/huiyinlehu/temp";
						new File(compressPath).mkdirs();
						compressPath = compressPath + File.separator +  (System.currentTimeMillis() + ".jpg");
					}
				})
				.setOnCancelListener(new OnCancelListener() {
					
					@Override
					public void onCancel(DialogInterface dialog) {
						if (null == mUploadMessage)
							return;
						mUploadMessage.onReceiveValue(null);
						mUploadMessage = null;
					}
				})
				.show();
	}

	

	/**
	 * 打开照相机
	 */
	private void openCarcme() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

		imagePaths = Environment.getExternalStorageDirectory().getPath()
				+ "/huiyinlehu/temp/" + (System.currentTimeMillis() + ".jpg");
		// 必须确保文件夹路径存在，否则拍照后无法完成回调
		File vFile = new File(imagePaths);
		if (!vFile.exists()) {
			File vDirPath = vFile.getParentFile();
			vDirPath.mkdirs();
		} else {
			if (vFile.exists()) {
				vFile.delete();
			}
		}
		cameraUri = Uri.fromFile(vFile);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraUri);
		startActivityForResult(intent, REQ_CAMERA);
	}

	/**
	 * 拍照结束后
	 */
	private void afterOpenCamera() {
		File f = new File(imagePaths);
		addImageGallery(f);
//		File newFile = FileUtils.compressFile(f.getPath(), compressPath);
	}

	/** 解决拍照后在相册中找不到的问题 */
	private void addImageGallery(File file) {
		ContentValues values = new ContentValues();
		values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
		values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
		getContentResolver().insert(
				MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
	}

	/**
	 * 本地相册选择图片
	 */
	private void chosePic() {
		FileUtils.delFile(compressPath);
//		Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); // "android.intent.action.GET_CONTENT"
//		String IMAGE_UNSPECIFIED = "image/*";
//		innerIntent.setType(IMAGE_UNSPECIFIED); // 查看类型
//		Intent wrapperIntent = Intent.createChooser(innerIntent, null);
//		startActivityForResult(wrapperIntent, REQ_CHOOSE);
		
		Intent intent = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, REQ_CHOOSE);
	}

	/**
	 * 选择照片后结束
	 * 
	 * @param data
	 */
	private Uri afterChosePic(Intent data) {

		// 获取图片的路径：
		String[] proj = { MediaStore.Images.Media.DATA };
		// 好像是android多媒体数据库的封装接口，具体的看Android文档
		@SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
		if (cursor == null) {
			UIHelper.showToast("上传的图片仅支持png或jpg格式");
			return null;
		}
		// 按我个人理解 这个是获得用户选择的图片的索引值
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		// 将光标移至开头 ，这个很重要，不小心很容易引起越界
		cursor.moveToFirst();
		// 最后根据索引值获取图片路径
		String path = cursor.getString(column_index);
		if (path != null
				&& (path.endsWith(".png") || path.endsWith(".PNG")
						|| path.endsWith(".jpg") || path.endsWith(".JPG"))) {
			File newFile = FileUtils.compressFile(path, compressPath);
			return Uri.fromFile(newFile);
		} else {
			UIHelper.showToast("上传的图片仅支持png或jpg格式");
		}
		return null;
	}

	/**
	 * 返回文件选择
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		// if (requestCode == FILECHOOSER_RESULTCODE) {
		// if (null == mUploadMessage)
		// return;
		// Uri result = intent == null || resultCode != RESULT_OK ? null
		// : intent.getData();
		// mUploadMessage.onReceiveValue(result);
		// mUploadMessage = null;
		// }

		if (null == mUploadMessage)
			return;
		Uri uri = null;
		if (requestCode == REQ_CAMERA) {
			afterOpenCamera();
			uri = cameraUri;
		} else if (requestCode == REQ_CHOOSE && null != intent) {
			uri = afterChosePic(intent);
		} else {
			uri = null;
		}
		mUploadMessage.onReceiveValue(uri);
		mUploadMessage = null;
		super.onActivityResult(requestCode, resultCode, intent);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
			mWebView.goBack();
			return true;
		} else {
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

}
